//
//  ViewController.m
//  GIFDecomposition
//
//  Created by Xwoder on 17/1/31.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"
#import <ImageIO/ImageIO.h>

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 沙盒路径
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSLog(@"%@", documentPath);
    
    // 加载GIF图片
    NSString *path = [[NSBundle mainBundle] pathForResource:@"computer_love" ofType:@"gif"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    // NSData转为CFDataRef
    CFDataRef dataRef = CFDataCreate(NULL, data.bytes, data.length);
    // CGImageSourceRef类型为ImageIO框架能直接处理的数据类型
    CGImageSourceRef imageSourceRef = CGImageSourceCreateWithData(dataRef, NULL);
    // GIF帧数
    size_t count = CGImageSourceGetCount(imageSourceRef);
    
    for (size_t i = 0; i < count; ++i) {
        // CGImageSourceCreateImageAtIndex函数
        // Creates a CGImage object for the image data associated with the specified index in an image source.
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, i, NULL);
        UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
        NSData *pngData = UIImagePNGRepresentation(image);
        
        NSString *destImageName = [NSString stringWithFormat:@"%tu.png", i];
        NSString *destPath = [documentPath stringByAppendingPathComponent:destImageName];
        [pngData writeToFile:destPath atomically:YES];
        
        CGImageRelease(imageRef);
    }
}

@end
